package main

import (
	"context"
	"errors"
	"fmt"
	"hook/models/config"
	"hook/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/gin-gonic/gin"
)

func init() {
	config.Init("conf/config.toml")
}

func main() {
	serverCfg := config.Cfg.Server
	engine := gin.New()
	engine.Use(Cors())
	if config.IsDebug() {
		engine.Use(gin.Recovery())
	}
	routers.EnableAPI(engine)
	srv := &http.Server{
		Addr:    fmt.Sprintf(":%d", serverCfg.Port),
		Handler: engine,
	}

	ctx, cancel := context.WithCancel(context.Background())
	go func() {
		if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
			log.Fatalln("Start server fail: ", err.Error())
		}
	}()
	log.Println("Server start ok:", serverCfg.Port)

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	defer cancel()

	log.Println("Shutting down server...")

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalln("Server forced to shutdown: ", err.Error())
	}

	log.Println("Server exiting")
}

func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		if method != "" {
			c.Header("Access-Control-Allow-Origin", "*") // 可将将 * 替换为指定的域名
			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
			c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
			c.Header("Access-Control-Allow-Credentials", "true")
		}
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()

	}
}
